package com.fast.controller.system;

import com.fast.controller.BaseController;
import com.fast.entity.SysUser;
import com.fast.services.SysUserService;
import com.fast.utils.Constant;
import com.fast.utils.bean.R;
import com.fast.utils.shiro.ShiroUtils;
import com.fast.utils.validator.Assert;
import com.fast.utils.validator.ValidatorUtils;
import com.fast.utils.validator.group.AddGroup;
import com.fast.utils.validator.group.UpdateGroup;
import lombok.AllArgsConstructor;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户管理
 * Created by xiehaitao on 2017/9/9.
 */
@RestController
@RequestMapping("/sys/user")
@AllArgsConstructor
public class UserController extends BaseController {

    SysUserService sysUserService;


    /**
     * 获取user 信息
     *
     * @return
     */
    @GetMapping("/username")
    public R userInfo() {
        return R.ok().put("username" , ShiroUtils.getUserEntity().getUsername());
    }


    /**
     * 分页查询 user 列表
     *
     * @param rows
     * @param user
     * @return
     */
    @RequestMapping("/list")
    public R userList(Integer rows, SysUser user) {
        return R.ok().put("page", sysUserService.queryPageListByWhere(Constant.pageSize, rows, user));
    }


    /**
     * 修改当前user 的密码
     *
     * @param password
     * @param newPassword
     * @return
     */
    @RequestMapping("/password")
    public R password(String password, String newPassword) {
        Assert.isNotBlank(newPassword, "新密码不为能空");
        Assert.isNotBlank( password , "原始密码不能为空");
        password = new Md5Hash(password, getSalt(), 2).toString();
        newPassword = new Md5Hash(newPassword, getSalt(), 2).toString();
        //更新密码
        int count = sysUserService.updatePassword(getUserId(), password, newPassword);
        if (count == 0) {
            return R.error("原密码不正确");
        }
        return R.ok();
    }


    /**
     * 修改user 信息
     *
     * @param user
     * @return
     */
    @PostMapping("/update")
    public R updateUser(SysUser user) {
        ValidatorUtils.validateEntity(user, UpdateGroup.class);
        sysUserService.updateSelective(user);
        return R.ok();
    }


    /**
     * 添加 user
     *
     * @param user
     * @return
     */
    @RequestMapping("/add")
    public R addUser(SysUser user) {
        ValidatorUtils.validateEntity(user, AddGroup.class);
        sysUserService.save(user);
        return R.ok();
    }


}
